﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Web;
using System.Web.Caching;
namespace UcAsp.Net.Comm
{
    public static class SpaceCache
    {
        private static  Cache cache = HttpRuntime.Cache;
        public static void CreateCache(object obj, string name)
        {

            object find = GetCache(name);
            if (find == null)
            {
                CacheDependency cd = new CacheDependency(AppDomain.CurrentDomain.BaseDirectory + "\\Web.config");
                cache.Add(name, obj, cd, DateTime.MaxValue, new TimeSpan(0,20,0),CacheItemPriority.Default,null);
            }
        }
        public static void CreateCache(object obj, string name, int absoluteexpriation)
        {

            object find = GetCache(name);
            if (find == null)
            {
                CacheDependency cd = new CacheDependency(AppDomain.CurrentDomain.BaseDirectory + "\\Web.config");
                cache.Insert(name, obj, cd, DateTime.UtcNow.AddHours(absoluteexpriation), TimeSpan.Zero);
            }
        }
        public static void CreateCache(object obj, string name, int absoluteexpriation, int slidingexpriation)
        {

            object find = GetCache(name);
            if (find == null)
            {
                CacheDependency cd = new CacheDependency(AppDomain.CurrentDomain.BaseDirectory + "\\Web.config");
                cache.Insert(name, obj, cd, DateTime.UtcNow.AddHours(absoluteexpriation), new TimeSpan(0, slidingexpriation, 0));
            }
        }
        public static void RemoveCache(string name)
        {

            object find = GetCache(name);
            if (find != null)
            {
                cache.Remove(name);
            }
        }
        public static object GetCache(string name)
        {
            try
            {
                object find = cache.Get(name);
                return find;
            }
            catch {
                return null;
            }
        }
        public static void RemoveAllCache()
        {
            IDictionaryEnumerator CacheEnum = cache.GetEnumerator();
            ArrayList al = new ArrayList();
            while (CacheEnum.MoveNext())
            {
                al.Add(CacheEnum.Key);
            }

            foreach (string key in al)
            {
                cache.Remove(key);
            } 
        }
    }
}
